<template>
  <div class="container">
    <div class="address">
      <!-- 地址渲染 -->
      <van-address-list
        :list="addressData"
        default-tag-text="默认"
        :switchable="false"
        class="address_list"
      />
      <van-divider
        :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 0' }"
        dashed
      />
    </div>
    <div class="goods_list">
      <!-- 购物车商品渲染 -->
      <van-card
        v-for="item in goodsList"
        :key="item.id"
        :num="item.count"
        :price="((item.goods_info.price / 100) * item.count).toFixed(2)"
        :desc="item.goods_info.detail_info"
        :title="item.goods_info.name"
        :thumb="item.goods_info.pic_url"
      />
    </div>
    <van-submit-bar
      :price="totalPrice"
      button-text="生成订单"
      @submit="show = true"
    >
      <template #tip>
        <!-- 备注 -->
        <van-field
          v-model="remark"
          rows="2"
          autosize
          label="备注"
          type="textarea"
          maxlength="50"
          placeholder="备注"
          show-word-limit
        />
      </template>
    </van-submit-bar>
    <!-- 动作面板 -->
    <van-action-sheet
      v-model:show="show"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @cancel="onCancel"
      @select="onSubmit"
    />
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref, watchEffect } from "vue";
import { getAddressList } from "@/api/address";
import { useRoute, useRouter } from "vue-router";
import useCartInfo from "@/stores/useCartInfo";
import { storeToRefs } from "pinia";
import { showSuccessToast } from "vant";
// 订单相关接口
import { orderAdd } from "@/api/order";
import { cartDelete } from "@/api/cart";
import { getGoodDetail } from "@/api/goods";

let route = useRoute();
let router = useRouter();

let cartStore = useCartInfo();
let { list } = storeToRefs(cartStore);
// 选中的地址
let addressData = ref([]);
// 购物车列表数据
let goodsList = ref([]);

// 备注
let remark = ref("");
// 动作面版的显隐状态
const show = ref(false);
// 动作面板选项
const actions = [
  { name: "微信", pay_type: 1 },
  { name: "支付宝", pay_type: 2 },
  { name: "云闪付", pay_type: 3 },
];
// 取消订单
let onCancel = async () => {
  let data = {
    pay_type: 0,
    remark: remark.value,
    status: "1",
    price: totalPrice.value,
    order_goods_infos: goodsList.value.map((item) => {
      return {
        goods_id: item.goods_id.toString(),
        count: item.count.toString(),
      };
    }),
    addressId: addressData.value[0].id,
  };
  //添加订单请求
  await orderAdd(data);
  showSuccessToast("生成订单成功");
  //判断是从购物车页面来的 还是直接商品详情购买来的
  if (route.query.checkGoodsId) {
    //删除仓库购物车数据 并刷新购物车仓库
    await cartDelete({ ids: goodsList.value.map((item) => item.id) });
    cartStore.getCartList();
  }
  router.replace("/home");
};

// 选择支付方式
let onSubmit = async (actions) => {
  //接口需要的参数
  let data = {
    pay_type: actions.pay_type,
    remark: remark.value,
    status: "2",
    price: totalPrice.value,
    order_goods_infos: goodsList.value.map((item) => {
      return {
        goods_id: item.goods_id.toString(),
        count: item.count.toString(),
      };
    }),
    addressId: addressData.value[0].id, //地址的id
  };
  //添加订单请求
  await orderAdd(data);
  showSuccessToast("生成订单成功");
  //判断是从购物车页面来的 还是直接商品详情购买来的
  if (route.query.checkGoodsId) {
    //删除仓库购物车数据 并刷新购物车仓库
    await cartDelete({ ids: goodsList.value.map((item) => item.id) });
    cartStore.getCartList();
  }
  router.replace("/home");
};

// 商品总价
let totalPrice = computed(() => {
  let countPrice = 0;
  goodsList.value.forEach((item) => {
    countPrice += item.count * item.goods_info.price;
  });
  return countPrice;
});

watchEffect(async () => {
  // 购物车选中的id数组 购物车页面来的
  if (route.query.checkGoodsId) {
    // split让字符串变成数组
    let goodsId = route.query.checkGoodsId.split(",");
    goodsList.value = cartStore.list.filter((item) =>
      goodsId.includes(item.id.toString())
    );
  }
});

onMounted(async () => {
  // 选中所需的地址数据 获取所有地址列表 过滤出id相同的
  let res = (await getAddressList({ limit: 100, page: 1 })).list || [];
  let addressList = res.filter((item) => item.id == route.query.addressId);
  //数据转换成组件需要的结构
  addressData.value = addressList.map((item) => {
    return {
      id: item.id,
      name: item.name,
      tel: item.phone,
      address: item.province + item.city + item.town + item.detail,
      isDefault: item.is_default == 1,
    };
  });
  //商品详情购买来的 goodList才这样获取
  if (route.query.goodsId) {
    let goodsInfo = await getGoodDetail(route.query.goodsId);
    goodsList.value = [
      {
        count: 1,//默认只买一个
        goods_id: route.query.goodsId,
        goods_info: goodsInfo,
      },
    ];
  }
});
</script>

<!-- 订单生成有2种方式 1.购物车到生成订单 2.商品详情直接购买到生成订单 -->

<style lang="scss" scoped>
.container {
  --van-submit-bar-z-index: 100;
  --van-address-list-add-button-z-index: 1;
  .address {
    padding-top: 20px;
    background-color: #fff;
    .address_list {
      --van-address-list-padding: 0;
      //   :deep样式穿透  将组件库内部的元素样式更改
      :deep(.van-badge__wrapper) {
        display: none;
      }
      .add-button-text {
        display: none;
      }
    }
  }
  .submit_box {
    background-color: #fff;
    bottom: 0;
    left: 0;
    right: 0;
    position: fixed;
    padding: 10px;
  }
}
</style>